package com.mouse.view;

import com.mouse.commen.Message;
import com.mouse.commen.MessageType;
import com.mouse.po.User;

import javax.swing.*;
import java.awt.*;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;

public class FriendListView extends JFrame {
    //苏：测试一下列表的配图和大小
    public static void main(String[] args) {
        User user = new User();
        FriendListView friendListView = new FriendListView(user.getUsername());
        friendListView.createFrame();
    }
    String username;
    public FriendListView(String username){
        this.username = username;
    }

    //可以滑动的好友列表
    JScrollPane jScrollPane = null;
    //放置好友列表的面板
    JPanel jPanel = null;
    //好友列表信息
    List<User> users;
    public void createFrame(){

        try{
            //和本机建立连接通信
            Socket socket = new Socket("localhost", 8881);
            //System.out.println("等待连接");
            Message message = new Message();
            message.setMessageType(MessageType.GET_USERS);

            //拿到和服务端建立的连接，获取输出流，向服务端输出
            OutputStream outputStream = socket.getOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
            objectOutputStream.writeObject(message);

            //从服务端得到好友信息
            InputStream inputStream = socket.getInputStream();
            ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
            Message acceptMessage = (Message) objectInputStream.readObject();
            users = acceptMessage.getUsers();

        }catch (Exception exception){
            exception.printStackTrace();
        }

        jPanel = new JPanel(new GridLayout(users.size(),1,15,15));
        for(int i = 0; i< users.size(); i++){
            ImageIcon imageIcon = new ImageIcon(FriendListView.class.getClassLoader().getResource("com/mouse/images/tx.png"));
            imageIcon.setImage(imageIcon.getImage().getScaledInstance(100, 100,Image.SCALE_DEFAULT));
            JLabel jLabel = new JLabel(users.get(i).getUsername(),imageIcon,JLabel.LEFT);
            jPanel.add(jLabel);
        }
        //网格布局放入可滚动的面板
        jScrollPane = new JScrollPane(jPanel);
        this.add(jScrollPane,BorderLayout.CENTER);

        this.setTitle(this.username + "好友列表");
        this.setBounds(900,600,400,600);
        this.setVisible(true);
        this.setResizable(false);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
